package com.feng.zhihao.apigeteway.util;

import java.util.Optional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.feng.zhihao.apigeteway.entity.InterfaceFieldGenerationRule;
import com.feng.zhihao.apigeteway.entity.InterfaceFieldInfo;
import com.feng.zhihao.apigeteway.entity.InterfaceInfo;
import com.feng.zhihao.apigeteway.gateway.ReqContext;
import com.feng.zhihao.apigeteway.gateway.bean.GENERATION_RULE;

public class GenerationRuleUtil {
	
	public static void generationResponse(InterfaceInfo interfaceInfo,ReqContext reqContext){
		interfaceInfo.getInterfaceFieldInfos()
		.stream()
		.forEach((ifi) -> {
			if(ifi.getInterfaceFieldPosition().startsWith("FIELD_POSITION_RES")){
				generationValue(ifi, reqContext);
			}
		});
	}
	public static void generationValue(InterfaceFieldInfo fieldInfo, ReqContext reqContext){
		if(fieldInfo.getInterfaceFieldInfo() != null){
			Object o = ParamsUtil.getValue(fieldInfo.getInterfaceFieldInfo(), reqContext);
			if(o == null){
				Object pValue=null;
				if(fieldInfo.getInterfaceFieldInfo().getInterfaceFieldType().equals("FIELD_TYPE_OBJECT")){
					pValue=new JSONObject();
				}
				if(fieldInfo.getInterfaceFieldInfo().getInterfaceFieldType().equals("FIELD_TYPE_ARRAY")){
					pValue=new JSONArray();
				}
				ParamsUtil.setValue(fieldInfo.getInterfaceFieldInfo(), pValue , reqContext);
			}
		}
		
		Object value=ParamsUtil.getValue(fieldInfo, reqContext);
		if(value != null){
			return;
		}
		if(fieldInfo.getInterfaceFieldType().equals("FIELD_TYPE_OBJECT")){
			value=new JSONObject();
		}else if(fieldInfo.getInterfaceFieldType().equals("FIELD_TYPE_ARRAY")){
			value=new JSONArray();
		}else{
			Optional<InterfaceFieldGenerationRule> optional = fieldInfo.getInterfaceFieldGenerationRules().stream().findFirst();
			if(optional.isPresent()){
				GENERATION_RULE generation_RULE = (GENERATION_RULE) BeanUtil.getBean(optional.get().getGenerationRuleType());
				value=generation_RULE.generationValue(fieldInfo, optional.get(), reqContext);	
			}else{
				value=null;
			}
			
		}
		ParamsUtil.setValue(fieldInfo, value, reqContext);
	}	
}
